/*
 * ELF executable loading
 * Copyright (c) 2003, Jeffrey K. Hollingsworth <hollings@cs.umd.edu>
 * Copyright (c) 2003, David H. Hovemeyer <daveho@cs.umd.edu>
 * $Revision: 1.29 $
 * 
 * This is free software.  You are permitted to use,
 * redistribute, and modify it as specified in the file "COPYING".
 */

#include <geekos/errno.h>
#include <geekos/kassert.h>
#include <geekos/ktypes.h>
#include <geekos/screen.h>  /* for debug Print() statements */
#include <geekos/pfat.h>
#include <geekos/malloc.h>
#include <geekos/string.h>
#include <geekos/user.h>
#include <geekos/elf.h>
#include <stdio.h>


/**
 * From the data of an ELF executable, determine how its segments
 * need to be loaded into memory.
 * @param exeFileData buffer containing the executable file
 * @param exeFileLength length of the executable file in bytes
 * @param exeFormat structure describing the executable's segments
 *   and entry address; to be filled in
 * @return 0 if successful, < 0 o
n error
 */
int Parse_ELF_Executable(char *exeFileData, 
	ulong_t exeFileLength,
    struct Exe_Format *exeFormat)
{


	int i=0;
	unsigned  short numPH;
	
	if (exeFileData == NULL)
	{
		goto error;	
	}
		
	elfHeader *our_ElfHeader = (elfHeader *)exeFileData;		
	if (!(our_ElfHeader->ident[0] == 0x7f && our_ElfHeader->ident[1] == 'E' && our_ElfHeader->ident[2] == 'L' && our_ElfHeader->ident[3] == 'F'))
	{
		goto error;	
	}
	numPH=our_ElfHeader->phnum;
	programHeader *our_ProgramHeader = (programHeader *)(exeFileData + our_ElfHeader->phoff);
	
	/* Controlar type ==2 y machine==3 */  
/*	Print("valor del ELF Header: %d\n",our_ElfHeader->phoff);*/
/*	Print("valor del program Header: %d\n\n",our_ProgramHeader->offset);*/
/*	Print("valor del phnum: %d\n",our_ElfHeader->phnum);*/
	
	if (numPH> EXE_MAX_SEGMENTS)
	{
		goto error;
	}
	
	
	for (i=0; i<numPH ;i++)
	{
		exeFormat->segmentList[i].offsetInFile = (our_ProgramHeader->offset);
		exeFormat->segmentList[i].lengthInFile = (our_ProgramHeader->fileSize);
		exeFormat->segmentList[i].startAddress = (our_ProgramHeader->vaddr);
		exeFormat->segmentList[i].sizeInMemory = (our_ProgramHeader->memSize);
		exeFormat->segmentList[i].protFlags = (our_ProgramHeader->flags);
	
/*		*/
/*		Print("-- Segmento nro: %d\n",i);		*/
/*		Print("offsetInFile: %d\n",exeFormat->segmentList[i].offsetInFile);*/
/*		Print("lengthInFile: %d\n",exeFormat->segmentList[i].lengthInFile);*/
/*		Print("startAddress: %d\n",exeFormat->segmentList[i].startAddress);*/
/*		Print("sizeInMemory: %d\n",exeFormat->segmentList[i].sizeInMemory);*/
/*		Print("protFlags: %d\n",exeFormat->segmentList[i].protFlags);*/
/*		Print ("--------------------------- \n");*/

		our_ProgramHeader += 1;

	}
	exeFormat->numSegments = i; 
	exeFormat->entryAddr = our_ElfHeader->entry;
	return(0);


	error:
		return(-1);	
    /* TODO("Parse an ELF executable image");*/


	
}

